import os
from typing import Dict
import yaml
from playwright.sync_api import Page, Locator

from get_project_path import project_path


class BasePage:
    def __init__(self, page: Page, yaml_path: str = None):
        self.page = page
        self.elements = self._load_elements(yaml_path) if yaml_path else {}

    def _load_elements(self, yaml_path: str) -> Dict[str, Dict[str, str]]:
        """加载指定YAML文件中的元素配置"""
        config_path = os.path.join(project_path,"pagefiles",yaml_path)
        with open(config_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f).get('elements', {})

    def locator(self, element_name: str) -> Locator:
        """根据元素名动态生成定位器"""
        element_config = self.elements.get(element_name)
        if not element_config:
            raise ValueError(f"元素 {element_name} 未在YAML中定义")

        locator_type = element_config['type']
        locator_value = element_config['value']

        if locator_type == 'xpath':
            return self.page.locator(f"xpath={locator_value}")
        elif locator_type == 'css':
            return self.page.locator(locator_value)
        else:
            raise ValueError(f"不支持的定位类型: {locator_type}")

    def take_screenshot(self, path: str):
        self.page.screenshot(path=os.path.join(project_path,"images",path),full_page=True)

    def get_session_storage(self):
        return self.page.evaluate('() => JSON.stringify(window.sessionStorage)')

    def get_current_url(self):
        return self.page.url